<script setup>
import { ref, reactive } from 'vue'
import { useRouter } from 'vue-router'
import { LockOutlined } from '@vicons/antd'
import md5 from 'js-md5'
import http from '../http'
import {
  useMessage,
  NGridItem,
  NGrid,
  NSpace,
  NButton,
  NModal,
  NCard,
  NForm,
  NFormItem,
  NInput,
  NIcon,
} from 'naive-ui'



// 路由
const router = useRouter()

// 返回主页
function goHome() {
  console.log('Nav.goHome => go home')
  router.push({ name: 'home' })
}

// 消息
const message = useMessage()

// 退出
function logout() {
  console.log('Nav.logout => logout')
  // 清理会话数据
  sessionStorage.removeItem('uid')
  sessionStorage.removeItem('name')
  sessionStorage.removeItem('token')
  sessionStorage.removeItem('role')
  // 转到登录页面
  router.push({ name: 'login' })
}

// 获取姓名
const name = sessionStorage.getItem('name')

// 获取用户ID
const uid = sessionStorage.getItem('uid')

// 用户密码修改
const user = reactive({
  oldPass: '',
  newPass: '',
  checkPass: '',
})

const title = `用户密码修改 [${uid}-${name}]`

// 表单
const formRef = ref(null)


// 校验规则
const rules = {
  oldPass: { required: true, trigger: 'blur', message: '请输入旧密码' },
  newPass: [
    { required: true, trigger: 'blur', message: '请输入新密码' },
    { validator: validatePassword, trigger: 'input', message: '新旧密码不能一样' },
  ],
  checkPass: [
    { required: true, trigger: 'blur', message: '请再次输入密码' },
    { validator: validateSamePassword, trigger: 'input', message: '两次输入的密码不一致' },
  ],
}

const show = ref(false)

// 校验新旧密码是否相同
function validateSamePassword(rule, value) {
  return value === user.newPass
}

function validatePassword(rule, value) {
  return value !== user.oldPass
}

// 密码修改
function updatePassword(e) {
  e.preventDefault()
  formRef.value.validate(err => {
    if (!err) {
      // 构造密码修改数据
      const password = {
        uid: uid,
        old_pass: md5(`${uid}-${user.oldPass}`),
        new_pass: md5(`${uid}-${user.newPass}`)
      }
      http.post('/api/user/password', password).then(res => {
        if (res.data.status) {
          show.value = false
          console.log('Nav.updatePassword => 用户密码修改成功')
          message.success('用户密码修改成功')
        } else {
          console.log(`Nav.updatePassword => 用户密码修改失败:${res.data.message}`)
          message.warning(res.data.message)
        }
      }).catch(err => {
        console.log(`Nav.updatePassword => 用户密码修改错误：${err.message}`)
        message.warning(err.message)
      })
    } else {
      // 字段校验失败
      for (let row of err) {
        console.log(`字段校验失败：${row[0].message}`)
      }
    }
  })
}

</script>

<template>
  <div class="nav">
    <n-grid x-gap="12" :cols="4" class="grid">
      <n-grid-item :offset="0">
        <div class="logo" @click="goHome">
          <img src="../../public/logo.svg" height="32" />
          <div style="margin-left: 15px;">ODM</div>
        </div>
      </n-grid-item>
      <n-grid-item :offset="2" class="operate">
        <n-space>
          <n-button quaternary @click="show = true">{{ name }}</n-button>
          <n-button quaternary @click="logout">退出</n-button>
        </n-space>
      </n-grid-item>
    </n-grid>
    <n-modal v-model:show="show" :mask-closable="false">
      <n-card style="width: 400px" :title="title" :bordered="false" closable @close="show = false">
        <n-form label-placement="left" label-width="auto" :rules="rules" ref="formRef" :model="user">
          <n-form-item label="旧密码" path="oldPass">
            <n-input type="password" v-model:value="user.oldPass" placeholder="请输入旧密码">
              <template #prefix>
                <n-icon>
                  <LockOutlined />
                </n-icon>
              </template>
            </n-input>
          </n-form-item>
          <n-form-item label="新密码" path="newPass">
            <n-input type="password" v-model:value="user.newPass" placeholder="请输入新密码">
              <template #prefix>
                <n-icon>
                  <LockOutlined />
                </n-icon>
              </template>
            </n-input>
          </n-form-item>
          <n-form-item label="验证密码" path="checkPass">
            <n-input type="password" v-model:value="user.checkPass" placeholder="请再次数据密码">
              <template #prefix>
                <n-icon>
                  <LockOutlined />
                </n-icon>
              </template>
            </n-input>
          </n-form-item>
          <n-form-item>
            <n-button type="primary" block size="large" @click="updatePassword">提交</n-button>
          </n-form-item>
        </n-form>
      </n-card>
    </n-modal>
  </div>
</template>

<style scoped>
.logo {
  margin-left: 35px;
  width: 80px;
  display: flex;
  align-items: center;
  font-size: large;
  cursor: pointer;
}

.grid {
  display: flex;
  align-items: center;
}

.operate {
  display: flex;
  justify-content: center;
}

.nav {
  height: 60px;
  display: flex;
  align-items: center
}
</style>